package com.dhecp.project.finance.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.project.base.domain.PartnerBankInfo;
import com.dhecp.project.base.mapper.PartnerBankInfoMapper;
import com.dhecp.project.common.domain.*;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.finance.domain.FinancesEventGroups;
import com.dhecp.project.finance.domain.PartnerBookedApply;
import com.dhecp.project.finance.domain.StoreAccount;
import com.dhecp.project.finance.mapper.FinancesEventGroupsMapper;
import com.dhecp.project.finance.mapper.PartnerBookedApplyMapper;
import com.dhecp.project.finance.mapper.StoreAccountMapper;
import com.dhecp.project.finance.service.StoreAccountService;
import com.dhecp.project.hr.domain.OperateCompanyApply;
import com.dhecp.project.hr.mapper.OperateCompanyApplyMapper;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import liquibase.pro.packaged.D;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 店铺入账申请 服务层
 * @author fxz
 * @version  2023.10.24
 */
@Service
public class StoreAccountServiceImpl extends BaseModuleServiceImpl implements StoreAccountService {

	@Autowired
	private StoreAccountMapper businessMapper;

	@Autowired
	private FinancesEventGroupsMapper financesEventGroupsMapper;
	
	@Autowired
	private SysDictionaryForFieldService dictionaryForFieldService;

	@Autowired
	private OperateCompanyApplyMapper operateCompanyApplyMapper;

	@Autowired
	private ModuleNidAndBidMapper moduleNidAndBidMapper;

	@Autowired
	private PartnerBookedApplyMapper partnerBookedApplyMapper;

	@Autowired
	private PartnerBankInfoMapper partnerBankInfoMapper;

	
	/**
	 * 查询前一单NID、BID
	 * @param nid 必要参数：当前 单据编码
	 * @return AjaxResult (data.nid 前一单NID， data.bid 前一单BID)
	 * @author DH-Xxj
	 * @throws Exception  
	 */
	@Override
	public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if (params.get("nid") == null || params.get("nid") == ""){
			params.put("nid", "0");   
		}
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = businessMapper.selectLastNid(params);
        if (moduleNID == null){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
        	return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
    	dataMap.put("nid", moduleNID.getNid().toString());
    	dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
	}
	
	/**
	 * 查询后一单NID、BID
	 * @param nid 必要参数：当前 单据编码
	 * @return AjaxResult (data.nid 后一单NID， data.bid 后一单BID)
	 * @author DH-Xxj
	 * @throws Exception  
	 */
	@Override
	public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
			return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
		}
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = businessMapper.selectNextNid(params);
        if (moduleNID == null){
        	dataMap.put("nid", "0");
        	dataMap.put("bid", "0");
        	return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
    	dataMap.put("nid", moduleNID.getNid().toString());
    	dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
	}
	
	/**
	 * 查询指定单nid的首记录
	 * @param nid 必要参数：当前 单据编码
	 * @return StoreAccount
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public StoreAccount queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
		return businessMapper.selectFirstRecordByNid(params);
	}
	
	/**
	 * 查询指定单nid的整单录
	 * @param nid 必要参数：当前 单据编码
	 * @return List - StoreAccount
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public List<StoreAccount> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return businessMapper.selectByNid(params);
	}
	
	/**
	 * 查询
	 * @param params
	 * @return List - StoreAccount
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
    public List<StoreAccount> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.select(params);
    }
	
	/**
	 * 分组（整单）查询
	 * @param params
	 * @return List - StoreAccount
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
    public List<StoreAccount> queryGroupList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return businessMapper.selectgroup(params);
    }
	
	/**
	 * 保存
	 * @param moduleTable 必要参数：功能唯一标识
	 * @param infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
	 * @param infoItems 必要参数：对应实体类的json格式字符串
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult saveData(Map<String, Object> params) {
		params.put("businessEntity", new StoreAccount());
		
		AjaxResult ajaxResult = this.saveDataBase(params);
		if (!"0".equals(ajaxResult.get("code").toString())){
			throw new RuntimeException(ajaxResult.get("msg").toString());
		}

		String resNid = "0";
		Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<StoreAccount> businessDataList = (List<StoreAccount>) ajaxResult.get("businessDataList");

    	List<RecordCheck> guidMapList = businessMapper.findRecords(infoMap.get("nid").toString());
    	Map<String, Object> guidMap = new HashMap<String, Object>();
    	if (!guidMapList.isEmpty() && guidMapList.size() > 0){
    		if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
    			throw new RuntimeException(MessageUtils.message("module.error.retry"));
    		}
        	for (RecordCheck recordCheck : guidMapList){
        		if (recordCheck != null && recordCheck.getGuid() != null){
            		guidMap.put(recordCheck.getGuid().toString(), "1");
        		}
        	}
    	}
    	
		if (businessDataList == null || businessDataList.size() == 0){
			resNid = "0";
		}else{
			resNid = infoMap.get("nid").toString();
			List<StoreAccount> insetList = new ArrayList<>();
			List<StoreAccount> updateList = new ArrayList<>();
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			Map<String, Object> params1 = new HashMap<String, Object>();
			params1.put("wherestr","t1.depositAccount IS NOT NULL");
			List<OperateCompanyApply> operateCompanyApplyList = operateCompanyApplyMapper.select(params1);
			for (StoreAccount businessData : businessDataList) {
				try {
					LocalDate.parse(businessData.getEndDate(), formatter).atStartOfDay();
				} catch (DateTimeParseException e) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return AjaxResult.error("交易创建日期格式不正确,请核实后再操作!例(2023-01-01)");
				}
	        	//根据收款账户获取备案公司
				if (businessData.getDepositAccount() != null){
					List<OperateCompanyApply> operateCompanyApplyListNew  = operateCompanyApplyList.stream().filter(operateCompanyApply ->
							operateCompanyApply.getDepositAccount().contains(businessData.getDepositAccount())).collect(Collectors.toList());
					if (operateCompanyApplyListNew.size() == 0){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return AjaxResult.error("收款账号:"+businessData.getDepositAccount()+",所对应运营公司不存在,请核实后再操作!");
					}
					OperateCompanyApply operateCompanyApply = operateCompanyApplyListNew.get(0);
					if (operateCompanyApply != null){
						String[] split = operateCompanyApply.getDepositAccount().split(",");
						for (String account : split){
							if (account.equals(businessData.getDepositAccount())){
								businessData.setvGsBm(operateCompanyApply.getvGsBm());
								businessData.setvGsJc(operateCompanyApply.getvGsJc());
								businessData.setvGsMc(operateCompanyApply.getvGsMc());
							}
						}
					}
				}else {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return AjaxResult.error("收款账号为空请核实后再操作!");
				}
	        	String guid = "";
	        	if (businessData.getGuid() == null){
	        		guid = RandomValueUtils.getGUID();
	        		businessData.setGuid(guid);
				}else{
	        		guid = businessData.getGuid().toString();
	        	}
				businessData.setaStatus("无");
				businessData.setStatus(0);
	        	
	        	for (String field : infoMap.keySet()){ //遍历非网格字段，并赋值到实体中
	        		Object fieldValue = infoMap.get(field);
	        		ReflectUtils.setValue(businessData, field, fieldValue);
	        	}
	        	
	        	if (guidMap.get(guid) == null){
					insetList.add(businessData);
	        	}else{
					updateList.add(businessData);
					guidMap.remove(guid);
	        	}
	        }
	        if (insetList.size() != 0){
				int insertLength = insetList.size();
				int i = 0;
				while (insertLength > 50) {
					businessMapper.batchInsert(insetList.subList(i, i + 50));

					i = i + 50;
					insertLength = insertLength - 50;
				}
				if (insertLength > 0) {
					businessMapper.batchInsert(insetList.subList(i, i + insertLength));
				}
			}
			if (updateList.size() != 0){
				int updateLength = updateList.size();
				int i = 0;
				while (updateLength > 50) {
					businessMapper.batchUpdate(updateList.subList(i, i + 50));

					i = i + 50;
					updateLength = updateLength - 50;
				}
				if (updateLength > 0) {
					businessMapper.batchUpdate(updateList.subList(i, i + updateLength));
				}
			}
		}

		List<String> deleteList = new ArrayList<>();
    	if (!guidMap.isEmpty()){
    		for (String guid : guidMap.keySet()){
				deleteList.add(guid);
    		}
			if (deleteList.size() != 0){
				int deleteLength = deleteList.size();
				int i = 0;
				while (deleteLength > 100) {
					businessMapper.batchDelete(deleteList.subList(i, i + 100));
					i = i + 100;
					deleteLength = deleteLength - 100;
				}
				if (deleteLength > 0) {
					businessMapper.batchDelete(deleteList.subList(i, i + deleteLength));
				}
			}
    	}
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }

	/**
	 * 手动匹配
	 * @param params
	 * @return
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public AjaxResult updatePP(Map<String, Object> params) {
		//查询店铺入账数据
		StoreAccount storeAccount = businessMapper.findById(params);
		if (storeAccount == null){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("店铺入账单不存在,请核实后再操作!");
		}
		//查询财务事件信息
		FinancesEventGroups financesEventGroups = financesEventGroupsMapper.findById(params);
		if (financesEventGroups == null){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("财务事件不存在,请核实后再操作!");
		}
		if (!storeAccount.getCurrencyCode().equals(financesEventGroups.getCurrency())){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("币种不匹配,请核实后再操作!");
		}
		if (!storeAccount.getrPrice().equals(new Double(financesEventGroups.getConvertedTotal().toString()))){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("实际支付金额不匹配,请核实后再操作!");
		}
		if (!storeAccount.getvGsBm().equals(financesEventGroups.getCompanyID())){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("运营公司不匹配,请核实后再操作!");
		}
		if (financesEventGroups.getaStatus().equals("匹配成功")){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("选择的财务事件信息已匹配,请核实后再操作!");
		}
		//获取店铺入账创建时间当前月份以及上一个月
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = dateFormat.parse(storeAccount.getEndDate());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int month = calendar.get(Calendar.MONTH) + 1;
		calendar.add(Calendar.MONTH, -1);
		int lastMonth = calendar.get(Calendar.MONTH) + 1;
		calendar.setTime(financesEventGroups.getEndDate());
		int monthXz = calendar.get(Calendar.MONTH) + 1;
		if (lastMonth != monthXz && month != monthXz){
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return AjaxResult.error("选择的财务事件时间不符合,请核实后再操作!");
		}
		//修改店铺入账单的财务事件id和财务事件匹配状态
		storeAccount.setaStatus("匹配成功");
		storeAccount.setFinancialEventGroupId(financesEventGroups.getFinancialEventGroupId());
		businessMapper.update(storeAccount);

		//修改财务事件的状态以及事件回款交易号
		financesEventGroups.setaStatus("匹配成功");
		financesEventGroups.setTransactionNum(storeAccount.getTransactionNum());
		financesEventGroupsMapper.update(financesEventGroups);
		return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
	}
	
	/**
	 * 删除
	 * @param infoItems 必要参数：对应实体类的json格式字符串
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<StoreAccount> businessDataList = JSON.parseArray(params.get("infoItems").toString(), StoreAccount.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (StoreAccount businessData : businessDataList) {
        	businessMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }
	
	/**
	 * 修改删除标志（预留）
	 * @param infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
        	businessMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }
	
	/**
	 * 流转  —— 添加流程任务、修改流程状态及生效标志
	 * @param tableDataId 必要参数：单据编码（nid）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowGo(Map<String, Object> params) {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		String nid = "0";
		if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
			return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
		}else{
			nid = params.get("tableDataId").toString();
		}
		params.put("nid", nid);
		List<StoreAccount> businessDataList = businessMapper.selectByNid(params);
		if (businessDataList == null || businessDataList.size() == 0){
			return AjaxResult.error(MessageUtils.message("module.error.nodata"));
		}else{
			infoMap.put("cid", businessDataList.get(0).getCid());
			infoMap.put("bUser", businessDataList.get(0).getbUser());
			infoMap.put("bDept", businessDataList.get(0).getbDept());
			infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
			infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
			infoMap.put("createTime", businessDataList.get(0).getCreateTime());
			params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
			params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
		}
		
		//流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
    	if (params.get("optType") == null || params.get("optType") == ""){
    		params.put("optType", "go");
    	}
		UpdateFlow updateFlow = new UpdateFlow();
    	updateFlow = this.FlowDealBase(params);

		ModuleNidAndBid moduleNidAndBid = null;
		Map<String, Object> params2 = null;
		Date date = null;
		if (updateFlow.getActiveFlow().equals("end")) {
			//查询头程货件最新数据
			params2 = new HashMap<String, Object>();
			params2.put("moduleTable", "TCW_PartnerBookedApply");
			moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params2);    //有事务控制，制单异常不跳过单号
			date = new Date();
		}
        for (StoreAccount businessData : businessDataList) {
        	updateFlow.setGuid(businessData.getGuid().toString());
        	businessMapper.updateFlow(updateFlow);

//        	//流程结束新增入账申请
//			if (updateFlow.getActiveFlow().equals("end")) {
//				try {
//					PartnerBookedApply partnerBookedApply = new PartnerBookedApply();
//					partnerBookedApply.setIid(businessData.getIid());
//					partnerBookedApply.setNid(moduleNidAndBid.getNid());
//					partnerBookedApply.setBid(moduleNidAndBid.getBid());
//					partnerBookedApply.setCid(businessData.getCid());
//					partnerBookedApply.setaUser(businessData.getaUser());
//					partnerBookedApply.setaDept(businessData.getaDept());
//					partnerBookedApply.setaPosition(businessData.getaPosition());
//					partnerBookedApply.setbUser(businessData.getbUser());
//					partnerBookedApply.setbDept(businessData.getbDept());
//					partnerBookedApply.setbPosition(businessData.getbPosition());
//					partnerBookedApply.setvBz(businessData.getCurrencyCode() + "&" + businessData.getbPrice());
//					partnerBookedApply.setvZdbz(businessData.getvZdbz());
//					partnerBookedApply.setCreateTime(businessData.getCreateTime());
//					partnerBookedApply.setUpdateTime(date);
//					partnerBookedApply.setEffectStock(true);
//					partnerBookedApply.setDeleted(true);
//					partnerBookedApply.setActiveFlow("end");
//					partnerBookedApply.setvGsBm(businessData.getvGsBm());
//					partnerBookedApply.setvGsMc(businessData.getvGsMc());
//					partnerBookedApply.setvGsJc(businessData.getvGsJc());
//					partnerBookedApply.setbPrice(businessData.getrPrice());
//					partnerBookedApply.setvJyLx("运营服务→店铺回款");
//					//获取合作商AMAZON的信息
//					params2.put("moduleTable", "TB_PartnerBankInfo");
//					params2.put("wherestr", "t1.partnerId = 'HZS00002'");
//					List<PartnerBankInfo> data = partnerBankInfoMapper.findData(params2);
//					if (data.size() == 0){
//						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//						return AjaxResult.error("合作商HZS00002不存在,新增入账申请失败!");
//					}
//
//					partnerBookedApply.setPartnerId(data.get(0).getPartnerId());
//					partnerBookedApply.setPartnerName(data.get(0).getPartnerName());
//					partnerBookedApply.setvKhh(data.get(0).getvKhh());
//					partnerBookedApply.setvYhZh(data.get(0).getvYhZh());
//					partnerBookedApply.setvDpHk("是");
//					partnerBookedApply.setWriteTime(date);
//					partnerBookedApplyMapper.insertFlow(partnerBookedApply);
//
//					//修改店铺入账的单号
//					businessData.setpBid(moduleNidAndBid.getBid());
//					businessMapper.update(businessData);
//				}catch (Exception e) {
//					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//					return AjaxResult.error("新增入账申请失败!");
//				}
//			}
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }
	
	/**
	 * 退回  —— 添加流程任务、修改流程状态及生效标志
	 * @param tableDataId 必要参数：单据编码（nid）
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowBack(Map<String, Object> params) {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		String nid = "0";
		if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
			return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
		}else{
			nid = params.get("tableDataId").toString();
		}
		params.put("nid", nid);
		List<StoreAccount> businessDataList = businessMapper.selectByNid(params);
		if (businessDataList == null || businessDataList.size() == 0){
			return AjaxResult.error(MessageUtils.message("module.error.nodata"));
		}else{
			infoMap.put("cid", businessDataList.get(0).getCid());
			infoMap.put("bUser", businessDataList.get(0).getbUser());
			infoMap.put("bDept", businessDataList.get(0).getbDept());
			infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
			infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
			infoMap.put("createTime", businessDataList.get(0).getCreateTime());
			params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
			params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
		}
		
		//流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
    	if (params.get("optType") == null || params.get("optType") == ""){
    		params.put("optType", "back");
    	}
		UpdateFlow updateFlow = new UpdateFlow();
    	updateFlow = this.FlowDealBase(params);

        for (StoreAccount businessData : businessDataList) {
        	if (businessData.getaStatus().equals("匹配成功")){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return AjaxResult.error("该单据已匹配财务事件,不允许操作!");
			}
        	updateFlow.setGuid(businessData.getGuid().toString());
        	businessMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

}
